import { createSlice } from '@reduxjs/toolkit'
import { delName } from './store_logo'

// 创建切片taskS
const taskSlice = createSlice({
  // 设置切片的名字
  name: 'task',
  // 设置次切片对应reducer中的初始状态
  initialState: {
    taskList: [],
    count: 220,
    userInfo: {
      name: 'zs',
      age: 20,
    },
  },
  // 编写业务代码处
  reducers: {
    setCount(state, action) {
      // state:redux中公共状态信息.基于immer库,不需要自己克隆
      // action: 派发的行为对象,我们无需考虑行为标识,传递的其他信息,都是以action.payload的方式传递进来的值
      state.count = action.payload
    },
    increment: state => {
      console.log('increment', state)
      state.count += 1
    },
    decrement: state => {
      state.count -= 1
    },
    incrementByAmount: (state, action) => {
      state.count += action.payload
    },
    setTaskList(state, action) {
      state.taskList = action.payload
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },

  },
  // extraReducers 用于处理其他切片中的action
  // 从其它切片中导入action生成函数, 在extraReducers中通过builder.addCase添加
  // dispatch该action时, 两个切片中函数都会触发 
  extraReducers: (builder) => {
    builder.addCase(delName, (state, action) => {
      state.userInfo = {}
    })
  },
})

// +++++++++++++++++++++++++++++ Selector 函数 +++++++++++++++++++++++++++++++++
export function getHotList(state) {
  const orangeList = state.task.taskList;
  return orangeList
}

// +++++++++++++++++++++++++++++ thunk 异步 +++++++++++++++++++++++++++++++++
// 将 thunk middleware 添加到 Redux store 后，它允许你将 thunk 函数 直接传递给 store.dispatch
// 调用 thunk 函数时总是将 (dispatch, getState) 作为它的参数
// 为了与 dispatch 普通 action 对象保持一致，我们通常将它们写为 thunk action creators，它返回 thunk 函数。
export const fetchUserData = (userId) => {
  return async (dispatch, getState) => {
    // dispatch({ type: 'FETCH_USER_REQUEST' });
    try {
      const response = await fetch(`https://cn.apihz.cn/api/xinwen/baidurg.php?id=88888888&key=88888888`);
      const data = await response.json();

      // dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
      dispatch(setTaskList(data.data));
    } catch (error) {
      // dispatch({ type: 'FETCH_USER_FAILURE', error });
    }
  };
};


// +++++++++++++++++++++++++++++ action creator +++++++++++++++++++++++++++++++++
// 从切片中获取actionCreator:此处结构的方法和上线reducers中的方法,仅仅是函数名相同;
// 结构后单独导出 setCount setTaskList
export let { setCount, setTaskList, increment, decrement, incrementByAmount } = taskSlice.actions
// 执行方法,返回需要派发的action,后期我们可以基于dispatch进行任务派发即可!!
// 切片返回中定义action.type为切片name/reducers属性
console.log(setCount([])) // {"type": "task/setCount", "payload": []}

console.log('taskSlice...', taskSlice)
// 切片实例对象
// actions
// caseReducers
// getInitialState
// getSelectors
// injectInto
// reducer
// reducerPath
// selectSlice
// selectors

export default taskSlice.reducer